package com.hoelg.hgc.webservices;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.util.Log;

import com.hoelg.hgc.DAO.Desc;
import com.hoelg.hgc.DAO.HGCUser;
import com.hoelg.hgc.constants.Utils;

public class RecupDesc extends WebServiceHGC {

	private static final String WS_NAME = "desc_R";

	public RecupDesc() throws NoSuchAlgorithmException, UnsupportedEncodingException{
		super(WS_NAME);
		try {
			this.webServiceParams.add(new BasicNameValuePair("u", HGCUser.getInstance().getLogin()));
			this.webServiceParams.add(new BasicNameValuePair("p", HGCUser.getInstance().getShaoneizedpwd()));
		} catch (Exception e) {
			Log.e("recupDesc_create", "Creation webService RecupDesc, catched : " + e.toString());
		}

	}

	public Object executeWebService() {

		beforeExec();

		try {
			super.executeWebServiceBase();

			JSONArray jArray = Utils.parseJSON(this.result);

			if (jArray.length() >0) {
				if (jArray.length() == 1 ) {
					JSONObject json_data = jArray.getJSONObject(0);
					if(json_data.length() == 2){
						String status = json_data.getString("status");
						if (status.equals("OK")) {
							JSONArray descs = json_data.getJSONArray("details");
							List<Desc> descRawRes = new ArrayList<Desc>();
							for (int i = 0; i< descs.length(); i++) {
								JSONObject jdesc = descs.getJSONObject(i);
								descRawRes.add(new Desc(jdesc.getInt("idC")
										, jdesc.getInt("idD")
										, jdesc.getString("cat")
										, jdesc.getString("dsc")
										, (jdesc.getString("type").equals("I"))
									)
								);
							}
							rawResult = descRawRes;
							resultatWS = "OK";
						}
						else {
							String details = json_data.getString("details");
							Log.e("err_in_adding_ln","error : " + details);
						}
					}
				}
			}
			else{
				resultatWS = "emptyResult";
			}
		}
		catch(Exception e){
			Log.e("recupdesc","erreur catchée dans " + WS_NAME + " : " + e.toString());
		}



		afterExec();

		return null;

	}

}
